<template>
  <view class="detail-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <text class="back-text">返回</text>
        </view>
        <view class="title">
          <text class="title-text">采购单详情</text>
        </view>
        <view class="action-btn" @click="showActions">
          <text class="action-text" v-if="role === 1 && (detailData.status === 0 || detailData.status === 1)">操作</text>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 详情内容 -->
    <scroll-view v-else class="detail-content" scroll-y="true">
      <!-- 基本信息 -->
      <view class="info-section">
        <view class="section-title">
          <text class="title-text">基本信息</text>
        </view>
        <view class="info-list">
          <view class="info-item">
            <text class="label">采购单ID</text>
            <text class="value">{{ detailData.id }}</text>
          </view>
          <view class="info-item">
            <text class="label">菜单日期</text>
            <text class="value">{{ formatDate(detailData.menu_date) }}</text>
          </view>
          <view class="info-item">
            <text class="label">菜单标题</text>
            <text class="value">{{ detailData.title }}</text>
          </view>
          <view class="info-item">
            <text class="label">菜单描述</text>
            <text class="value">{{ detailData.description || '暂无描述' }}</text>
          </view>
          <view class="info-item">
            <text class="label">供应商</text>
            <text class="value">{{ detailData.supplier && detailData.supplier.name || '未指定' }}</text>
          </view>
          <view class="info-item">
            <text class="label">采购员</text>
            <text class="value">{{ detailData.purchaser && detailData.purchaser.name || '未指定' }}</text>
          </view>
          <view class="info-item">
            <text class="label">状态</text>
            <view class="status-tag" :class="[getStatusClass(detailData.status)]">
              <text class="status-text">{{ getStatusText(detailData.status) }}</text>
            </view>
          </view>
          <view class="info-item">
            <text class="label">创建时间</text>
            <text class="value">{{ formatDateTime(detailData.create_time) }}</text>
          </view>
        </view>
      </view>

      <!-- 菜品列表 -->
      <view class="dish-section">
        <view class="section-title">
          <text class="title-text">菜品列表</text>
          <view class="dish-count">
            <text class="count-text">{{ dishList.length }}道菜品</text>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="dishList.length === 0" class="empty-dish">
          <image src="/static/image/no_permission.png" class="empty-icon" mode="aspectFit"></image>
          <text class="empty-text">暂无菜品</text>
          <text class="empty-desc">请先选择菜品</text>
        </view>

        <!-- 菜品列表 -->
        <view v-else class="dish-list">
          <view v-for="(dish, index) in dishList" :key="dish.id" class="dish-item">
            <view class="dish-info">
              <view class="dish-name">
                <text class="name-text">{{ dish.dish && dish.dish.name }}</text>
              </view>
              <view class="dish-category">
                <text class="category-text">{{ dish.dish && dish.dish.category }}</text>
              </view>
            </view>

            <view class="dish-details">
              <view class="detail-row" v-if="role === 1">
                <text class="detail-label">官方参考价格</text>
                <text class="detail-value">¥{{ dish.base_price }}</text>
              </view>
              <view class="detail-row" v-if="role === 1">
                <text class="detail-label">供应商报价</text>
                <text class="detail-value">¥{{ dish.supplier_quoted_price }}</text>
              </view>
              <view v-if="dish.actual_price" class="detail-row">
                <text class="detail-label">实际采购价格-供应商</text>
                <text class="detail-value">¥{{ dish.actual_price }}</text>
              </view>
              <view class="detail-row">
                <text class="detail-label">计划采购数量-食堂</text>
                <text class="detail-value">{{ dish.planned_quantity }}{{ dish.dish && dish.dish.unit }}</text>
              </view>
              <view v-if="dish.actual_quantity" class="detail-row">
                <text class="detail-label">实际数量-供应商</text>
                <text class="detail-value">{{ dish.actual_quantity }}{{ dish.dish && dish.dish.unit }}</text>
              </view>
              <view v-if="dish.actual_quantity" class="detail-row">
                <text class="detail-label">实际数量-验收</text>
                <text class="detail-value">{{ dish.actual_quantity2 }}{{ dish.dish && dish.dish.unit }}</text>
              </view>
            </view>

            <view v-if="dish.quality_rating" class="dish-rating">
              <text class="rating-label">品质评价</text>
              <text class="rating-text">{{ dish.quality_rating }}</text>
            </view>
            <view v-if="dish.planned_remark" class="dish-remark">
              <text class="remark-label">采购备注</text>
              <text class="remark-text">{{ dish.planned_remark }}</text>
            </view>
            <view v-if="dish.remark" class="dish-remark">
              <text class="remark-label">验收备注</text>
              <text class="remark-text">{{ dish.remark }}</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 操作菜单 -->
    <u-popup v-model="showActionPopup" mode="bottom">
      <view class="action-menu">
        <view class="action-item" @click="editWorkorder">
          <text class="action-text">编辑采购单</text>
        </view>
        <view class="action-item" @click="selectDishes">
          <text class="action-text">选择菜品</text>
        </view>
        <view v-if="detailData.status === 0" class="action-item" @click="publishWorkorder">
          <text class="action-text">发布采购单</text>
        </view>
        <view v-if="detailData.status === 2" class="action-item" @click="confirmReceipt">
          <text class="action-text">确认收货</text>
        </view>
        <view class="action-item cancel" @click="closeActions">
          <text class="action-text">取消</text>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import api from "../../config/api.js";

export default {
  data() {
    return {
      workorderId: '',
      loading: true,
      detailData: {},
      dishList: [],
      showActionPopup: false,

      // 采购单状态
      statusList: [
        { key: 0, name: '草稿' },
        { key: 1, name: '待采购' },
        { key: 2, name: '采购中' },
        { key: 3, name: '已收货' },
        { key: 4, name: '已完成' }
      ]
    }
  },

  onLoad(options) {
    this.$store.dispatch('getUserInfo')
    if (options.id) {
      this.workorderId = options.id;
      this.loadDetailData();
    }
  },

  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 加载详情数据
    loadDetailData() {
      this.loading = true;

      // 获取采购单详情
      api.getDailyMenu(this.workorderId).then(response => {
        this.detailData = response;

        // 获取菜品列表
        return this.loadDishList();
      }).catch(error => {
        console.error('加载采购单详情失败:', error);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      }).finally(() => {
        this.loading = false;
      });
    },

    // 加载菜品列表
    loadDishList() {
      return api.getDailyMenuItemList({
        daily_menu_id: this.workorderId
      }).then(response => {
        this.dishList = response || [];
      }).catch(error => {
        console.error('加载菜品列表失败:', error);
      });
    },

    // 获取状态样式类
    getStatusClass(status) {
      const statusMap = {
        0: 'status-pending',
        1: 'status-processing',
        2: 'status-completed',
        3: 'status-accepted',
        4: 'status-published'
      };
      return statusMap[status] || 'status-pending';
    },

    // 获取状态文本
    getStatusText(status) {
      const statusItem = this.statusList.find(item => item.key === status);
      return statusItem ? statusItem.name : '未知状态';
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 格式化日期时间
    formatDateTime(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },

    // 显示操作菜单
    showActions() {
      this.showActionPopup = true;
    },

    // 关闭操作菜单
    closeActions() {
      this.showActionPopup = false;
    },

    // 编辑采购单
    editWorkorder() {
      this.showActionPopup = false;
      uni.navigateTo({
        url: `/pages/workorder/create?id=${this.workorderId}`
      });
    },

    // 选择菜品
    selectDishes() {
      this.showActionPopup = false;
      uni.navigateTo({
        url: `/pages/workorder/dishes?id=${this.workorderId}`
      });
    },

    // 发布采购单
    publishWorkorder() {
      this.showActionPopup = false;
      uni.showModal({
        title: '确认操作',
        content: '确定要发布该采购单吗？',
        success: (res) => {
          if (res.confirm) {
            this.loading = true;
            api.updateDailyMenu(this.workorderId, {
              status: 1
            }).then(() => {
              uni.showToast({
                title: '发布成功',
                icon: 'success'
              });
              this.loadDetailData();
            }).catch(error => {
              uni.showToast({
                title: '发布失败：' + error.message,
                icon: 'none'
              });
            }).finally(() => {
              this.loading = false;
            });
          }
        }
      });
    },

    // 确认收货
    confirmReceipt() {
      this.showActionPopup = false;
      uni.navigateTo({
        url: `/pages/workorder/receipt?id=${this.workorderId}`
      });
    }
  }
}
</script>

<style lang="scss">
.detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

// 顶部导航
.header {
  background-color: #fff;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .back-btn {
      .back-text {
        font-size: 32rpx;
        color: #666;
      }
    }

    .title {
      .title-text {
        font-size: 36rpx;
        color: #333;
        font-weight: 600;
      }
    }

    .action-btn {
      .action-text {
        font-size: 32rpx;
        color: #FFC300;
        font-weight: 500;
      }
    }
  }
}

// 加载状态
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;

  .loading-text {
    font-size: 28rpx;
    color: #666;
  }
}

// 详情内容
.detail-content {
  height: calc(100vh - 120rpx);
  padding: 32rpx;
}

// 信息区块
.info-section, .dish-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;

  .section-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32rpx;

    .title-text {
      font-size: 36rpx;
      color: #333;
      font-weight: 600;
    }

    .dish-count {
      .count-text {
        font-size: 28rpx;
        color: #666;
      }
    }
  }
}

// 信息列表
.info-list {
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 0;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .label {
      font-size: 28rpx;
      color: #666;
    }

    .value {
      font-size: 28rpx;
      color: #333;
      text-align: right;
      flex: 1;
      margin-left: 32rpx;
    }

    .status-tag {
      padding: 8rpx 16rpx;
      border-radius: 8rpx;
      font-size: 24rpx;

      &.status-pending {
        background-color: #fff8e1;
        color: #ff9800;
      }

      &.status-processing {
        background-color: #e3f2fd;
        color: #2196f3;
      }

      &.status-completed {
        background-color: #e8f5e8;
        color: #4caf50;
      }

      &.status-accepted {
        background-color: #e8f5e8;
        color: #4caf50;
      }

      &.status-published {
        background-color: #f3e5f5;
        color: #9c27b0;
      }

      .status-text {
        font-weight: 500;
      }
    }
  }
}

// 空状态
.empty-dish {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 80rpx 0;

  .empty-icon {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 24rpx;
    opacity: 0.6;
  }

  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 12rpx;
  }

  .empty-desc {
    font-size: 24rpx;
    color: #ccc;
  }
}

// 菜品列表
.dish-list {
  .dish-item {
    background-color: #f8f8f8;
    border-radius: 12rpx;
    padding: 24rpx;
    margin-bottom: 24rpx;

    .dish-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24rpx;

      .dish-name {
        .name-text {
          font-size: 32rpx;
          color: #333;
          font-weight: 600;
        }
      }

      .dish-category {
        .category-text {
          font-size: 24rpx;
          color: #666;
          background-color: #e8e8e8;
          padding: 8rpx 16rpx;
          border-radius: 8rpx;
        }
      }
    }

    .dish-details {
      .detail-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .detail-label {
          font-size: 26rpx;
          color: #666;
        }

        .detail-value {
          font-size: 26rpx;
          color: #333;
          font-weight: 500;
        }
      }
    }

    .dish-rating {
      margin-top: 24rpx;
      padding-top: 24rpx;
      border-top: 1rpx solid #e8e8e8;

      .rating-label {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 12rpx;
        display: block;
      }

      .rating-text {
        font-size: 26rpx;
        color: #333;
        line-height: 1.5;
      }
    }

    .dish-remark {
      margin-top: 24rpx;
      padding-top: 24rpx;
      border-top: 1rpx solid #e8e8e8;

      .remark-label {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 12rpx;
        display: block;
      }

      .remark-text {
        font-size: 26rpx;
        color: #333;
        line-height: 1.5;
      }
    }
  }
}

// 操作菜单
.action-menu {
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  overflow: hidden;

  .action-item {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 32rpx;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    &.cancel {
      .action-text {
        color: #999;
      }
    }

    .action-text {
      font-size: 32rpx;
      color: #333;
    }
  }
}
</style>
